package com.fast.modules.acd.interceptor;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptorAdapter;
import org.springframework.messaging.support.MessageHeaderAccessor;

import com.fast.common.WebSocketConstant;
import com.fast.common.auth.HeaderToken;
import com.fast.modules.acd.service.QueueService;
import com.fast.modules.acd.service.SeatService;
import com.google.common.collect.Lists;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AuthInterceptor extends ChannelInterceptorAdapter implements WebSocketConstant {
	
	@Autowired
	SeatService seatService;
	
    @Autowired
    Map<String, String> sessionMap;
    
    @Autowired
    QueueService queueService;

	
	@Override
	public Message<?> preSend(Message<?> message, MessageChannel channel) {
		
		StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
		
		
		if (StompCommand.CONNECT.equals(accessor.getCommand())) {
			List<String> users = accessor.getNativeHeader("username");
			
			if(users != null && users.size() >= 1) {
				String username = users.get(0);
				log.debug("客户端ID是" + username); 
	            accessor.setUser(new HeaderToken(username));
				sessionMap.put(accessor.getSessionId(), username);
			}
			
			


        }
		
		//判断坐席签入-> 就绪的时候，从Header中直接取出坐席id和坐席技能列表，调用上线接口
		if (StompCommand.SUBSCRIBE.equals(accessor.getCommand())) {
			
			String destination = accessor.getDestination();
			
			if(SEAT_SUBSCRIBE_TOPIC_NAME.equals(destination)) {
				String username = accessor.getUser().getName();
				if(username != null) {
					List<String> skills = accessor.getNativeHeader("skills");
					if(skills != null && skills.size() > 0) {
						String[] array = StringUtils.split(skills.get(0), ",");
						seatService.online(username, Lists.newArrayList(array));
					} 
					

					
				}
			}


        }
		
		//连接中断的Command无法获取到destination,所以无法根据地址判断出是客服还是客户
		if (StompCommand.DISCONNECT.equals(accessor.getCommand())) {
			
			System.out.println(accessor.getSessionId());

			String username = sessionMap.get(accessor.getSessionId());
			
			log.debug(username + "断开连接");
			//坐席下线
			seatService.offline(username);
			//从队列中清除
			queueService.cancel(username);
            //用户挂断
			seatService.hangup(username);
			
			//TODO 连接中断之后，需要修改存储数据，这里需要取出username并判断出token是客户还是客服
        }
		
		
		return message;
	}

}
